<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页</title>
    <!-- 依 赖 样 式 -->
    <link rel="stylesheet" href="../module/pear/css/pear.css"/>
    <style>
        #log p {
            word-wrap: break-word;
            word-break: break-all;
            margin: 5px 8px 0 10px;
        }
    </style>
</head>
<body class="pear-container">
<button class="pear-btn" id="test"> 测试</button>
<button class="pear-btn pear-btn-warming" deploy>配置</button>
<button class="pear-btn pear-btn-success" id="add"> 新增任务</button>
<button class="pear-btn pear-btn-primary" loading> 开始任务</button>
<button class="pear-btn pear-btn-danger" stop> 停止任务</button>
<div style="width: 100%">
    <div class="layui-form" style="width: 500px;display: inline-block" id="taskList">
        <table class="layui-table">
            <colgroup>
                <col width="30">
                <col width="160">
                <col width="130">
            </colgroup>
            <thead>
            <tr>
                <th>选择</th>
                <th>任务名称</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="tasks">
            </tbody>
        </table>
        <p style="margin-left: 45%" hidden id="null">还没有任务</p>
    </div>
    <div style="margin-left: 60px;display: inline-block;position: absolute;width: 420px;">
        <div class="layui-form" style="width: 100%;height: 350px" id="runList">
            <table class="layui-table">
                <colgroup>
                    <col width="160">
                    <col width="260">
                </colgroup>
                <thead>
                <tr>
                    <th>任务名称</th>
                    <th>进度</th>
                </tr>
                </thead>
                <tbody id="runner">
                </tbody>
            </table>
        </div>
        <div style="height: 200px;width: 100%;border:1px solid #000000;overflow:auto" id="log">
            <p> > Log</p>
        </div>
    </div>
</div>
</body>
<!-- 依 赖 脚 本 -->
<script src="../module/layui/layui.js"></script>
<script src="../module/pear/pear.js"></script>
<script>
    var state = false
    let taskList = []
    var cacheTab = {}
    var deployDom = null
    let date = new Date()
    let dom;
    layui.use(['layer', 'jquery', 'form', 'toast', 'tool', 'button', 'request', 'element'], function () {
        let $ = layui.jquery
        let tool = layui.tool
        let request = layui.request

        $("#test").click(() => {
            alert(JSON.stringify({
                type: 'function',
                method: 'test'
            }))
        })

        $("#add").click(() => {
            parent.layui.tab.addTabOnlyByElem('contents', {
                id: 'add',
                title: '添加任务',
                url: parent.window.jsConnector.HTML_PATH + "/taskForm.html",
                close: true
            })
        })

        $("[loading]").click(function () {
            if (!state) {
                let runTaskList = []
                //获取勾选的任务
                $('#taskList').find('[name=chickTask]:checked').each(function () {
                    runTaskList.push($(this).val())
                })
                if (runTaskList.length > 0) {
                    tool.loading.Load("正在部署..")
                    console.log(JSON.stringify(runTaskList))
                    alert(JSON.stringify({
                        type: 'function',
                        method: 'runTask',
                        data: runTaskList
                    }))
                } else
                    tool.toast.warning('', '请选择要执行的任务');
            } else
                tool.toast.warning('', '已经开始执行任务');
        })
        $("[stop]").click(function () {
            if (state) {
                tool.loading.Load("正在终止..")
                alert(JSON.stringify({
                    type: 'function',
                    method: 'shutTask'
                }))
            }
        })

        $("[deploy]").click(function () {
            if (!state) {
                request.get({
                    url: parent.window.jsConnector['API_PREFIX'] + '/getDeploy',
                    msg: false
                }, (res) => {
                    console.log(JSON.stringify(res))
                    layer.open({
                        type: 2,
                        title: '全局配置',
                        shade: 0.1,
                        area: ['80%', '80%'],
                        btn: ['确定'],
                        content: parent.window.jsConnector.HTML_PATH + '/deploy.html',
                        yes: function (index, layero) {
                            const iframeWin = window[layero.find('iframe')[0]['name']];
                            const formData = iframeWin.saveDeploy();
                            tool.loading.Load("正在保存..")
                            alert(JSON.stringify({
                                type: 'function',
                                method: 'saveDeploy',
                                data: formData
                            }))
                            layer.close(index);
                        },
                        success: function (layero, index) {
                            deployDom = layer.getChildFrame('body', index);
                            var iframeWin = window[layero.find('iframe')[0]['name']];
                            iframeWin.init(res);
                        },
                        end: function (layero, index) {
                            deployDom = null
                        }
                    });
                })
            } else
                tool.toast.warning('提示', '请停止任务再做配置');
        })

        parent.window.contentWin = window;
    })

    function edit(i) {
        if (state) {
            layui.tool.toast.warning('提示', '正在执行任务，请停止后再修改');
        } else
            parent.layui.tab.addTabOnlyByElem('contents', {
                id: 'edit' + i,
                title: '编辑任务[' + taskList[i] + ']',
                url: parent.window.jsConnector.HTML_PATH + "/taskForm.html?index=" + i,
                close: true
            })
    }

    function copy(i) {
        if (state) {
            layui.tool.toast.warning('提示', '正在执行任务，请停止后再修改');
        } else
            parent.layui.tab.addTabOnlyByElem('contents', {
                id: 'edit' + i,
                title: '复制任务[' + taskList[i] + ']',
                url: parent.window.jsConnector.HTML_PATH + "/taskForm.html?copy=1&index=" + i,
                close: true
            })
    }

    function del(i) {
        if (state) {
            layui.tool.toast.warning('提示', '正在执行任务，请停止后再修改');
        } else {
            alert(JSON.stringify({
                type: 'function',
                method: 'delTask',
                index: i
            }))
        }
    }

    function getTaskList(data) {
        taskList = data
        let $ = layui.jquery
        $('#tasks').html('')
        let trs = ''
        $.each(data, function (i, t) {
            trs += '<tr>' +
                '<td><input type="checkbox" name="chickTask" value="' + i + '"></td>' +
                '<td>' + t + '</td>' +
                '<td> ' +
                '<input type="button" class="pear-btn pear-btn-warming pear-btn-xs "  onclick="edit(' + i + ')" value="编辑"/> ' +
                '<input type="button" class="pear-btn pear-btn-danger pear-btn-xs " onclick="del(' + i + ')" value="删除"/> ' +
                '<input type="button" class="pear-btn pear-btn-success pear-btn-xs " onclick="copy(' + i + ')" value="复制"/> ' +
                '</td>' +
                '</tr>'
        })
        $('#tasks').html(trs)
        if (data.length === 0)
            $('#null').show()
        else
            $('#null').hide()
        layui.form.render()
    }

    function reload() {
        //获取任务列表
        alert(JSON.stringify({
            type: 'function',
            method: 'getTaskList'
        }))
    }

    function addLog(log) {
        layui.jquery('#log').append(' <p> <span style="color: red">></span> [' + date.toLocaleDateString() + ' ' + date.toLocaleTimeString().toLocaleString() + '] ' + log + '</p>')
        layui.jquery('#log').scrollTop(layui.jquery('#log')[0].scrollHeight);
    }

    function doRunning(res) {
        if (res.code === 0) {
            state = true
            dom = layui.button.load({
                elem: '[loading]'
            })
            infoRunner(res.data)
        } else
            layui.tool.toast.error('', '启动失败：' + res.message);
        layui.tool.loading.remove(500)
        reload()
    }

    function shut(res) {
        if (res.code === 0) {
            state = false
            dom.stop(function () {
                layui.tool.toast.warning('', '任务已停止');
            });
            infoRunner([])
            reload()
        } else
            layui.tool.toast.error('', '终止失败：' + res.message);
        layui.tool.loading.remove(500)
    }

    function done() {
        state = false
        dom.stop(function () {
            layui.tool.toast.warning('', '任务已完成');
        });
        infoRunner([])
        reload()
    }

    function infoRunner(data) {
        let $ = layui.jquery
        let html = ''
        $.each(data, (i, t) => {
            html += '<tr>' +
                '<td>' + t.name + '</td>' +
                '<td>' +
                '<div class="layui-progress layui-progress-big" lay-filter="task' + t.index + '" lay-showPercent="true">' +
                '<div class="layui-progress-bar layui-bg-blue" lay-percent="0%">' +
                '</div>' +
                '</div>' +
                '</td>' +
                '</tr>'
        })
        $('#runner').html(html)
        layui.element.render()
    }

    function refRunnerProgress(data) {
        layui.element.progress('task' + data.index, data.progress + '%');
    }

</script>
</html>